<template>
  <div class="class-manage">
    <div class="header">
      <div class="search">
        <el-form
          ref="formRef"
          :inline="true"
          :model="form"
          :rules="rules"
          class="demo-form-inline"
        >
          <el-form-item label="班级名称：" prop="calssName">
            <el-input v-model="form.calssName" placeholder="请输入班级名称" />
          </el-form-item>
          <el-form-item label="年级：" prop="grade">
            <el-input-number
              v-model="form.grade"
              :min="2020"
              :max="new Date().getFullYear()"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="btns">
        <el-button @click="saveAddClass()">保存</el-button>
        <!-- <el-button>批量删除</el-button> -->
      </div>
    </div>
    <!-- 导入学生 -->
    <div class="export-btn">
      <span>导入学生：</span>
      <el-button text type="primary" @click="importStudent()"
        >Excel导入<i class="iconfont icon-daoru1"></i
      ></el-button>
      <el-button text type="primary" @click="HistoryImport()"
        >历史班级导入<i class="iconfont icon-daoru1"></i
      ></el-button>
    </div>
    <!-- 表格 -->
    <div class="chapter-list">
      <el-table
        ref="multipleTableRef"
        :data="paginatedTableData"
        empty-text="暂无数据"
        row-key="id"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :index="calculateIndex"
        />
        <el-table-column property="name" label="学生姓名" width="200" />
        <el-table-column property="userNumber" label="学号" width="200" />
        <el-table-column property="sexName" label="性别" width="150" />
        <el-table-column
          property="telephoneNumber"
          label="联系方式"
          width="200"
        />
        <el-table-column property="email" label="邮箱" width="200" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button
              :disabled="scope.row.sourceIsExcel"
              size="small"
              text
              type="primary"
              @click="removeStudent(scope.$index, scope.row)"
              style="color: #457aff"
            >
              移除
            </el-button>
            <!-- <el-button size="small" text type="primary" @click="handleEnd(scope.$index, scope.row)" style="color: #457AFF;">
              结课
            </el-button>
            <el-button
              style="margin-left: 0px;color: #457AFF;"
              text
              type="primary"
              size="small"
              @click="handleManage(scope.$index, scope.row)"
            >
              管理学生
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-if="total > 0"
      />
    </div>

    <!-- Excel导入 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogExcel"
      width="500px"
      @close="dialogExcel = false"
      center
    >
      <div class="dialog-body">
        <div>
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
            :limit="1"
            :show-file-list="false"
            accept=".xlsx,.xls"
          >
            <el-button round>上传Excel</el-button>
          </el-upload>
          <span
            @click="downloadTemplate"
            style="cursor: pointer; color: #457aff; text-decoration: none"
            >学生信息模板.xls
            <i class="iconfont icon-tubiaozhizuo-"></i>
          </span>
        </div>
        <!-- 显示上传的文件名 -->
        <div v-if="uploadedFileName" class="uploaded-file">
          <span>{{ uploadedFileName }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="background-color: #457aff"
            type="primary"
            @click="confirmImport()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 历史班级导入 -->
    <el-dialog
      v-model="dialogHistory"
      :close-on-click-modal="false"
      class="dialog-history"
      width="660px"
      center
    >
      <div class="dialog-content">
        <el-form-item label="选择班级：">
          <el-cascader
            :options="optionsClass"
            v-model="optionsClassValue"
            :show-all-levels="false"
            @change="handleItemChange"
          ></el-cascader>
        </el-form-item>
        <div class="select-all">
          <div class="select-all-title">
            <el-checkbox
              :checked="isCheckedAll"
              v-model="checkAllFlag"
              @change="checkAll"
            >
              全选</el-checkbox
            >
          </div>
          <div class="select-all-list">
            <el-checkbox-group v-model="checkModel" @change="handleChecked">
              <el-checkbox
                v-for="(item, index) in selectAll"
                :value="item.id"
                :key="index"
                >{{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button
          class="button-style"
          type="primary"
          color="#457aff"
          @click="HistoryImportSave()"
          >保 存</el-button
        >
        <el-button class="button-style" @click="dialogHistory = false"
          >取 消</el-button
        >
      </template>
    </el-dialog>

    <!-- 学生重复提示弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      class="dialog-history-tips"
      v-model="dialogHistoryTips"
      width="500px"
    >
      <div class="dialog-content">
        <div class="content-box">
          <p v-for="item in historyTipsInfo" :key="item">{{ item }}</p>
        </div>
        <div class="content-notation">
          <!-- 注: 1、继续导入，重复学生从原班级移除。2、不导入，重复学生在原班级保留 。 -->
          <el-radio v-model="historyImportRadio" label="1"
            >继续导入，重复学生从原班级移除。</el-radio
          >
          <el-radio v-model="historyImportRadio" label="2"
            >不导入，重复学生在原班级保留。</el-radio
          >
        </div>
      </div>
      <template #footer>
        <el-button
          class="button-style"
          type="primary"
          color="#457aff"
          @click="HistoryTipImport()"
          >确认</el-button
        >
        <el-button class="button-style" @click="HistoryTipUnImport()"
          >取消</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import eventBus from "@/utils/eventBus";

export default {
  data() {
    return {
      courseId: "",
      currentPage: 1,
      pageSize: 10,
      form: {
        calssName: "",
        grade: 2020,
      },
      rules: {
        calssName: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
        grade: [{ required: true, message: "请输入年级", trigger: "blur" }],
      },
      tableData: [],
      dialogExcel: false,
      dialogHistory: false,
      selectAll: [],
      isCheckedAll: false,
      checkAllFlag: false,
      checkModel: [], //选中数组
      CheckedAllArr: [], //全选数组
      optionsClass: [],
      optionsClassValue: [],
      uploadedFileName: "", // 新增：用于存储上传的文件名
      uploadedFile: null,
      total: 0,
      dialogHistoryTips: false,
      historyTipsInfo: [],
      historyImportRadio: "1",
      // 用户对错误提示作出的决定 true：继续导入 ；false：过滤 ；null：没有作出决定
      errorFlag: "",
    };
  },
  computed: {
    // 添加计算属性来处理分页数据
    paginatedTableData() {
      return this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
  },
  methods: {
    // 计算表格序号
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    // 保存导入的班级
    saveAddClass() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "保存中...",
            background: "rgba(0, 0, 0, 0.7)",
          });
          const formData = new FormData();
          formData.append("file", this.uploadedFile);
          const studentIds = this.tableData.map((item) => item.id);
          this.$axios
            .post(
              `/tes/course/${this.courseId}/class?studentIds=${studentIds}&studentclassId=&name=${this.form.calssName}&grade=${this.form.grade}&errorFlag=${this.errorFlag}`,
              formData
            )
            .then((res) => {
              if (res.code == 100105) {
                loading.close();
                this.historyTipsInfo = res.data;
                this.dialogHistoryTips = true;
                return;
              }
              // 课程id变更，重新存储
              localStorage.setItem("courseId", res.data);
              this.$message.success(res.message);
              // 通过eventBus通知父组件更新disabledNav状态
              eventBus.emit("updateClassInfo");
              this.$router.push(
                "/aiTeaching/courseSystem/teachingManage/classManage"
              );
            })
            .finally(() => {
              loading.close();
            });
        }
      });
    },

    // 移除导入历史班级学生
    removeStudent(index, row) {
      this.$confirm("确定要移除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .get(
            `/tes/course/class/remove_history?courseId=${this.courseId}&studentUserId=${row.id}`
          )
          .then((res) => {
            this.$message.success("移除成功");
            this.getOldList();
          });
      });
    },

    importStudent() {
      this.dialogExcel = true;
      this.uploadedFileName = ""; // 清空之前上传的文件名
    },
    // 处理文件变化
    handleFileChange(file) {
      this.uploadedFile = file.raw;
      this.uploadedFileName = file.name;
      console.log("上传的文件:", file.name);
    },
    handleRemove(file) {
      this.uploadedFile = null;
      this.uploadedFileName = "";
      console.log("移除文件:", file.name);
    },

    // 确认导入
    confirmImport() {
      if (!this.uploadedFile) {
        this.$message.error("请上传文件");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const formData = new FormData();
      formData.append("file", this.uploadedFile);
      this.$axios.post("/tes/user/model/parse", formData).then((res) => {
        this.tableData = res.data;
        this.total = res.data.length;
        this.currentPage = 1; // 重置到第一页
        this.$message.success("导入成功");
        this.dialogExcel = false;
      });
      this.$refs.uploadRef.clearFiles();
      loading.close();
    },
    // 历史班级导入
    HistoryImport() {
      this.$axios
        .get(`/tes/course/natural-class_and_history?courseid=${this.courseId}`)
        .then((res) => {
          this.optionsClass = res.data;
          this.dialogHistory = true;
        });
      this.optionsClassValue = [];
      this.selectAll = [];
      this.checkModel = [];
      this.checkAllFlag = false;
    },

    handleItemChange(data) {
      this.checkModel = [];
      this.checkAllFlag = false;
      let found = false;

      // 如果没有选择子节点（data[1]为undefined），直接清空数据
      if (!data || data.length < 2 || !data[1]) {
        this.selectAll = [];
        this.setCheckedAllArr();
        return;
      }

      for (let i = 0; i < this.optionsClass.length; i++) {
        for (let j = 0; j < this.optionsClass[i].children.length; j++) {
          if (this.optionsClass[i].children[j].value == data[1]) {
            this.selectAll = this.optionsClass[i].children[j].selectAll;
            this.setCheckedAllArr();
            found = true;
            break;
          }
        }
        if (found) break;
      }

      // 如果没有找到匹配的子节点，清空数据
      if (!found) {
        this.selectAll = [];
        this.setCheckedAllArr();
      }
    },
    setCheckedAllArr() {
      this.CheckedAllArr = [];
      this.selectAll.forEach((item, index) => {
        this.CheckedAllArr.push(item.id);
      });
    },

    //全选
    checkAll(val) {
      this.checkModel = val ? this.CheckedAllArr : [];
    },

    //单选
    handleChecked() {
      this.isCheckedAll = this.checkModel.length == this.selectAll.length;
      this.checkAllFlag = this.checkModel.length == this.selectAll.length;
    },

    // 历史班级导入保存
    HistoryImportSave() {
      if (!this.checkModel || this.checkModel.length === 0) {
        this.$message.warning("请选择要导入的学生");
        return;
      }
      this.$axios
        .post(
          `/tes/course/class/import_student?courseId=${this.courseId}&classId=${this.optionsClassValue[1]}`,
          this.checkModel
        )
        .then((res) => {
          this.$message.success("导入成功");
          this.dialogHistory = false;
          this.tableData = res.data;
          this.total = res.data.length;
          this.currentPage = 1; // 重置到第一页
        });
    },

    // 移除历史班级导入后的获取列表
    getOldList() {
      this.$axios
        .post(`/tes/course/class/import_student?courseId=${this.courseId}`, [])
        .then((res) => {
          this.tableData = res.data;
          this.total = res.data.length;
          // 如果当前页没有数据了，回到上一页
          const maxPage = Math.ceil(this.total / this.pageSize);
          if (this.currentPage > maxPage && maxPage > 0) {
            this.currentPage = maxPage;
          }
        });
    },

    // 重复提示导入
    HistoryTipImport() {
      // 调用保存数据函数
      this.errorFlag = this.historyImportRadio == 1 ? true : false;
      this.saveAddClass();
    },
    // 重复提示不导入
    HistoryTipUnImport() {
      // 关闭提示
      this.dialogHistoryTips = false;
      // 重置提示信息
      this.historyTipsInfo = [];
    },

    // 下载学生信息模板
    downloadTemplate() {
      const loading = this.$loading({
        lock: true,
        text: "下载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.$axios({
        method: "get",
        url: "/tes/user/model/download/student",
        responseType: "blob",
      })
        .then((response) => {
          // 创建blob对象
          const blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });

          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.download = "学生信息模板.xls"; // 确保文件名有正确的扩展名

          // 触发下载
          document.body.appendChild(link);
          link.click();

          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success("下载成功");
        })
        .catch((error) => {
          this.$message.error("下载失败");
          console.error("下载错误:", error);
        })
        .finally(() => {
          loading.close();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.class-manage {
  background-color: #fff;
  padding: 10px 40px 40px 80px;
  box-sizing: border-box;
  min-height: 550px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        font-size: 16px;
        color: #252e54;
      }
      .search-btn {
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #a5beff;
        color: #457aff;
        line-height: 40px;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .el-button {
        background: #457aff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
  .export-btn {
    display: flex;
    align-items: center;
    margin-top: 20px;
    span {
      font-size: 16px;
      color: #252e54;
    }
    .el-button {
      margin-left: 0;
      color: #457aff;
      &:hover {
        background-color: #fff;
      }
      i {
        font-size: 16px;
        margin-left: 5px;
      }
    }
  }
  .chapter-list {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;
    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
  }

  .dialog-body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    > div {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .el-button {
      color: #457aff;
      border: 1px solid #457aff;
      margin-right: 10px;
      &:hover {
        background-color: #457aff;
        color: #fff;
      }
    }
    .uploaded-file {
      margin-top: 15px;
      span {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }
    }
  }

  .dialog-content {
    padding: 20px 50px;
    .select-all-title {
      border-bottom: 1px solid #e5e5e5;
      padding-bottom: 10px;
    }
    .select-all-list {
      padding-top: 10px;
      .el-checkbox {
      }
    }
  }
}
</style>

